package com.ds.util;

import com.ds.client.exception.ProfileNotFoundException;
import com.ds.model.Enums.OUTPUT_FORMAT;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 *
 * @author exploredhiraj
 */
public class PomParser {

    List<ProfileDetails> listOfProfiles;
    Map<String, Node> mapOfNodes = new HashMap<String, Node>();

    public PomParser(File inputPomFile) {
        try {
            // Create a factory          
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // Use the factory to create a builder          
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(inputPomFile);
            // Get element            
            Node firstNode = doc.getFirstChild();
            traverseNodesAndCreateProfiles(firstNode);
        } catch (Exception e) {
            System.out.print("Error" + e);
        }

    }

    private void setAllProfileDetails(String... profilesToBeCompared) throws ProfileNotFoundException {
        listOfProfiles = new ArrayList<ProfileDetails>();
        ProfileDetails pd;
        for (int i = 0; i < profilesToBeCompared.length; i++) {
            pd = new ProfileDetails();
            pd.setProfileName(profilesToBeCompared[i]);
            try {
                pd.setNode(mapOfNodes.get(profilesToBeCompared[i]));
            } catch (NullPointerException npe) {
                System.out.print("Profile " + profilesToBeCompared[i] + " not found in the POM file");
                throw new ProfileNotFoundException("Profile " + profilesToBeCompared[i] + " not found in the POM file");
            }
            listOfProfiles.add(pd);
        }
    }

    private void traverseNodesAndCreateProfiles(Node node) {
        Node parentNode = null;
        String mapProfile = null;
        if (node.getNodeName() != null && node.getNodeName().equals("id")) {
            mapProfile = node.getTextContent();
            parentNode = node.getParentNode();
            mapOfNodes.put(mapProfile, parentNode);
        }

        if (node.hasChildNodes()) {
            for (int i = 0; i < node.getChildNodes().getLength(); i++) {
                traverseNodesAndCreateProfiles(node.getChildNodes().item(i));
            }
        }
    }

    public String generateOutput(OUTPUT_FORMAT format, String outputHtmlFileName, String... profilesToBeCompared) throws IOException, ProfileNotFoundException {
        setAllProfileDetails(profilesToBeCompared);
        OutputGenerator og = new OutputGenerator();
        if (format.equals(OUTPUT_FORMAT.HTML)) {
            return og.generateHtmlOutput(outputHtmlFileName, listOfProfiles);
        } else {
            return null;
        }
    }
}
